package logic

import (
	"context"
	"demo/internal/errorx"
	"demo/internal/svc"
	"demo/internal/types"
	"demo/model"
	"strconv"

	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/core/stores/redis"
)


type ServeyClasifyDeleteLogic struct{
	logx.Logger
	ctx context.Context
	rds *redis.Redis
	svcCtx *svc.ServiceContext
	model model.ServeyClassifyModel
	modelSSC model.SevSevClfModel
}

func NewServeyClassifyDeleteLogic(ctx context.Context,svcCtx *svc.ServiceContext)*ServeyClasifyDeleteLogic{
	
	rds, err := redis.NewRedis(redis.RedisConf{
		Host: svcCtx.Config.Redis.Host,
		Pass: svcCtx.Config.Redis.Pass,
		Type: svcCtx.Config.Redis.Type,
	})
	if err != nil {
		logx.Errorf("redis init error: %v", err)
	}
	return &ServeyClasifyDeleteLogic{
		Logger: logx.WithContext(ctx),
		ctx: ctx,
		svcCtx: svcCtx,
		rds: rds,
		model: model.NewServeyClassifyModel(svcCtx.Orm,svcCtx.GormDB),
		modelSSC: model.NewSevSevClfModel(svcCtx.Orm),
	}
}

func (l *ServeyClasifyDeleteLogic)Delete(req *types.IdRequest)(resp *types.ServeyClassifyCreateResponse,err error){
	payload,ok := l.ctx.Value("payload").(string)
	if !ok {
		return nil,errorx.NewBizError(500,"用户ID获取失败")
	}
	userId,err := strconv.ParseInt(payload,10,64)
	if err != nil{
		return nil,errorx.NewBizError(500,"字符串格式转换错误")
	}

	// step1 judge this servey-class is own
	sc,err := l.model.FindOne(l.ctx,req.Id)
	if err != nil && err == model.ErrNotFound {
		return nil,errorx.NewBizError(500,"未找到对应的数据")
	}
	if sc.CreatorId != userId {
		return nil,errorx.NewBizError(500,"违规操作")
	}

	// 删除redis中的数据
	l.rds.DelCtx(l.ctx,ServeyClassifyDetailPrefix + strconv.FormatInt(req.Id,10))

	// step2 delete
	err = l.modelSSC.DeleteBySCId(l.ctx,nil,req.Id)
	if err != nil {
		return nil,errorx.NewBizError(500,err.Error())
	}
	err = l.model.Delete(l.ctx,req.Id)
	if err != nil {
		return nil,errorx.NewBizError(500,"数据库操作错误，请重试～～")
	}
	return &types.ServeyClassifyCreateResponse{
		CommonResponse: types.CommonResponse{
			Code: 200,
			Msg: "delete success",
		},
	},nil
}